//
//  AppDelegate.m
//  yilutongxing
//  患者版
//  Created by  on 17/3/10.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import <EventKit/EventKit.h>
#import "AppDelegate.h"
#import <AFNetworking.h>
#import "QMUIConfigurationTemplate.h"
#import <QMUIKit/QMUIKit.h>
#import "NetworkDelegate.h"
#import "YZECommunityViewController.h"
#import "YZEConsultViewController.h"
#import "YZEHomeViewController.h"
#import "YZEMyinfoTableViewController.h"
#import "YZEPatientViewController.h"
#import "YZESigninViewController.h"
#import "UserDefaultsTools.h"
#import "IQKeyboardManager.h"
#import "PQCatchErrorLog.h"
#import "DataUtils.h"
#import "UITabBar+BFMAddition.h"

@interface AppDelegate ()<UITabBarControllerDelegate, NSURLSessionTaskDelegate>
@property (nonatomic, strong) EKEventStore *eventStore;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    debugLog(@"Document Path:%@", [DataUtils getDocumentsPath]);//打印当前Document Path，供测试需要
    //QMUI库全局配置
    // 启动QMUI的配置模板
    [QMUIConfigurationTemplate setupConfigurationTemplate];
    // 将全局的控件样式渲染出来
    [QMUIConfigurationManager renderGlobalAppearances];
    //键盘管理
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    //崩溃日志
    [PQCatchErrorLog catchLog];
    [PQCatchErrorLog printErrorLog];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self refreshToken];
    return YES;
}
//初始化登录界面
- (void)initLoginController{
    UIStoryboard *signinupSB = [UIStoryboard storyboardWithName:@"signinup" bundle:nil];
    YZESigninViewController *signinView = [signinupSB instantiateViewControllerWithIdentifier:@"signinVC"];
    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:signinView];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
}
//初始化主体界面
- (void)initTabBarController
{
    [[YZENetwork sharedInstace] getRequestWithUrl:URL_UserInfo parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        
        NSDictionary *dic=responseObject;
        [UserDefaultsTools saveUserDefaultsObject:dic forKey:@"userInfo"];
        
    }];
    
    _tabBarController = [[DGTTabBarController alloc] init];
    _tabBarController.navigationController.navigationBarHidden=YES;
    _tabBarController.delegate = self;
    
    YZEHomeViewController * home =[[YZEHomeViewController alloc]init];
    YZECommunityViewController *community =[[YZECommunityViewController alloc]init];
    YZEPatientViewController *patient = [[YZEPatientViewController alloc]init];
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"YZEConsultView" bundle:[NSBundle mainBundle]];
    YZEConsultViewController *consult = [sb instantiateViewControllerWithIdentifier:@"consultVC"];
    //YZEConsultViewController *consult = [[YZEConsultViewController alloc] init];
    //用户中心界面
    UIStoryboard *userinfoSB = [UIStoryboard storyboardWithName:@"userinfo" bundle:nil];
    YZEMyinfoTableViewController *myinfoTableView = [userinfoSB instantiateViewControllerWithIdentifier:@"myinfoVC"];
    
    UINavigationController *Navgation0=[[UINavigationController alloc]initWithRootViewController:home];
    UINavigationController *Navgation1=[[UINavigationController alloc]initWithRootViewController:community];
    UINavigationController *Navgation2=[[UINavigationController alloc]initWithRootViewController:patient];
    UINavigationController *Navgation3=[[UINavigationController alloc]initWithRootViewController:consult];
    UINavigationController *Navgation4=[[UINavigationController alloc]initWithRootViewController:myinfoTableView];
    
  //  Navgation0.navigationBarHidden=YES;
    Navgation1.navigationBarHidden=YES;
    //Navgation1.navigationItem.hidesBackButton=YES;
    Navgation2.navigationBarHidden=YES;
    //Navgation2.navigationItem.hidesBackButton=YES;
    Navgation3.navigationBarHidden=YES;
    //Navgation3.navigationItem.hidesBackButton=YES;
    Navgation4.navigationBarHidden=YES;
    //Navgation4.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    //Navgation4.navigationItem.hidesBackButton=YES;
    
    self.tabBarController.viewControllers=@[Navgation0,Navgation1,Navgation2,Navgation3,Navgation4];
    self.window.rootViewController = _tabBarController;
    [self.window makeKeyAndVisible];
    
    //请求未读消息数
    [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingString:@"/api/message-boxes/unreadCount/CONSULTATION_MESSAGE"]
                                       parameters:nil
                                         delegate:self
                                       requestTag:1
                                     successBlock:^(id responseObject)
    {
        NSNumber *count = (NSNumber*)responseObject;
        if ([count compare:@0]==NSOrderedDescending) {
            [self.tabBarController setBadgeWithString:@"" toIndex:3];
        }
        else {
            [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingString:@"/api/message-boxes/unreadCount/SYSTEM_MESSAGE"]
                                               parameters:nil
                                                 delegate:self
                                               requestTag:2
                                             successBlock:^(id responseObject)
            {
                NSNumber *count = (NSNumber*)responseObject;
                if ([count compare:@0]==NSOrderedDescending) {
                    [self.tabBarController setBadgeWithString:@"" toIndex:3];
                }
            }];
        }
    }];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //[[LKAlarmMamager shareManager] handleOpenURL:url];
    return YES;
}

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    //[[LKAlarmMamager shareManager] didReceiveLocalNotification:notification];
}

//当点击tabBarItem时触发该操作  UITabBarControllerDelegate中的一个方法
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    NSArray *array = tabBarController.viewControllers;
    for (int i=0; i<array.count; i++) {
        if (viewController == array[i]) {
            [tabBarController setSelectedIndex:i];
        }
    }
}

#pragma mark - 登录相关业务逻辑
- (void)refreshToken{
    NSDictionary *tokenDic = [UserDefaultsTools getTokenAndTimestamp];
    if (!tokenDic) {
        [self initLoginController];
    }else{
        long last_token_timestamp = [(NSNumber*)tokenDic[@"timestamp"] longValue];
        long current_timestamp = [[NSDate date] timeIntervalSince1970];
        if (current_timestamp - last_token_timestamp <= 24*60*60) {
            //发送刷新token请求
            NSString *token = tokenDic[@"token"];
            token = [token stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            NSString *url = [NSString stringWithFormat:@"%@%@%@", BASE, @"/api/refresh?token=", token];
            NSString *authorizion = [NSString stringWithFormat:@"Bearer %@",token];
            __weak typeof(self) weakself = self;
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
            [request setHTTPMethod:@"POST"];
            [request setValue:authorizion forHTTPHeaderField:@"Authorization"];
            NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
            NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (!error) {
                        NSHTTPURLResponse *repo = (NSHTTPURLResponse*)response;
                        if (repo.statusCode==200) {
                            [weakself OnRefreshTokenSuccess:data];
                        }
                        else {
                            [self initLoginController];
                        }
                    }else{
                        //请求失败
                        [self initLoginController];
                    }
                });
            }];
            [task resume];
            
            UIViewController *vc = [UIViewController new];
            self.window.rootViewController = vc;
        }
        else {
            [self initLoginController];
        }
    }
}

#pragma mark - 网络代理
//刷新token成功，进入app
- (void)OnRefreshTokenSuccess:(NSData*)data{
    //请求成功
    NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    NSString *token = responseObject[@"data"][@"id-token"];
    [UserDefaultsTools saveToken:token];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:[NSString stringWithFormat:@"Bearer %@", token] forKey:@"Authorization"];
    [YZENetwork sharedInstace].dicHTTPHeaderField = dic;
    [self initTabBarController];
}
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.allowRotation) {//如果设置了allowRotation属性，支持全屏
        return UIInterfaceOrientationMaskAll;
    }
    return UIInterfaceOrientationMaskPortrait;//默认全局不支持横屏
}

- (void)rotate2Portrait{
    //强制归正：
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val =UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}

#pragma mark - 静态方法，业务逻辑
- (EKEventStore *)sharedEventStore{
    if (!_eventStore) {
        _eventStore = [[EKEventStore alloc]init];
    }
    return _eventStore;
}

@end
